<template>
  <d2-container>
    <template slot="header">策略期初盈亏-修改</template>
    <div style="margin-bottom:10px;font-size:14px">
      <span style="color:red">* </span>为必填项
    </div>
    <el-card shadow="never" class="d2-mb">
      <el-form
        class="filter-container"
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="85px"
      >
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="策略名称" prop="strategy_name">
              <el-input
                v-model="ruleForm.strategy_name"
                clearable
                :disabled="true"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="策略ID" prop="strategy_id">
              <el-input
                v-model="ruleForm.strategy_id"
                clearable
                :disabled="true"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="日期" prop="date">
              <el-date-picker
                v-model="ruleForm.date"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择日期时间"
                style="width:100%;"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never" class="d2-mb">
      <el-form :model="tradeData" ref="spotFrom">
        <el-table
          :data="tradeData"
          border
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          @selection-change="futuresRow"
        >
          <el-table-column type="selection" width="40"> </el-table-column>
          <el-table-column type="index" :index="indexMethod" label="序号">
          </el-table-column>
          <el-table-column label="类型">
            <template slot-scope="scope">
              <el-select
                v-model="scope.row.type"
                filterable
                allow-create
                :disabled="true"
              >
                <el-option label="现货" value="1"></el-option>
                <el-option label="期货" value="2"></el-option>
                <el-option label="期权" value="3"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="品名/品种"></el-table-column>
          <el-table-column label="实现盈亏" prop="achieve_profit_loss">
            <template slot-scope="scope">
              <el-form-item
                :prop="scope.$index + '.achieve_profit_loss'"
                :rules="rules.achieve_profit_loss"
              >
                <el-input
                  placeholder="请输入内容"
                  type="number"
                  v-model="scope.row.achieve_profit_loss"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="持有盈亏" prop="holding_profit_loss">
            <template slot-scope="scope">
              <el-form-item
                :prop="scope.$index + '.holding_profit_loss'"
                :rules="rules.holding_profit_loss"
              >
                <el-input
                  placeholder="请输入内容"
                  type="number"
                  v-model="scope.row.holding_profit_loss"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-card>
    <el-button
      type="primary"
      size="mini"
      style="float:right;margin-left: 10px;"
      @click="submitForm('ruleForm', 'spotFrom')"
    >
      保存
    </el-button>
  </d2-container>
</template>

<script>
import { editAndLossInfo } from "@/api/url_info.js";
import { profitAndLossInfo } from "@/api/url_info.js";
export default {
  //策略期初盈亏修改
  name: "ProfitAndLoss_E",
  components: {},
  data() {
    return {
      dialogVisible: false,
      tradeData: [],
      ruleForm: {
        //基础信息
        strategy_name: "",
        strategy_id: "",
        date: ""
      },
      listRow: [],
      title: "",
      state: "",
      rules: {
        date: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change"
          }
        ],
        achieve_profit_loss: [
          { required: true, message: "请输入实现盈亏", trigger: "blur" }
        ],
        holding_profit_loss: [
          { required: true, message: "请输入持有盈亏", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.strategyInfo();
  },
  methods: {
    // async listAll() {
    //   // 获取传过来的参数
    //   if (this.$route.params.editList) {
    //     console.log("获取传过来的参数", this.$route.params.editList);
    //     this.ruleForm = this.$route.params.editList[0];
    //     this.tradeData.unshift(this.ruleForm);
    //     let state = this.$route.params.editList[1];
    //     this.state = state;
    //   }
    // },
    //网格信息
    strategyInfo() {
      profitAndLossInfo({ strategy_id: this.$route.query.strategy_id })
        .then(res => {
          let data = res.result.results[0];
          this.ruleForm = data;
          this.tradeData.unshift(this.ruleForm);
          this.state = this.$route.query.state;
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //保存
    submitForm(formName, spotName) {
      let obj2 = {};
      let d = new Date(this.tradeData[0].date);
      let resDate =
        d.getFullYear() + "-" + (d.getMonth() + 1) + "-" + d.getDate();
      this.tradeData[0].date = resDate;
      console.log("678678678", this.tradeData[0].date);
      this.tradeData.forEach(item => {
        switch (item.type) {
          case "现货":
            item.type = "1";
            break;
          case "期货":
            item.type = "2";
            break;
          case "期权":
            item.type = "3";
            break;
        }
        obj2["id"] = item.id;
        obj2["achieve_profit_loss"] = item.achieve_profit_loss;
        obj2["holding_profit_loss"] = item.holding_profit_loss;
        obj2["strategy_id"] = item.strategy_id;
        obj2["trade_id"] = item.trade_id;
        obj2["date"] = item.date;
        obj2["type"] = item.type;
        obj2["strategy_name"] = item.strategy_name;
      });
      this.tradeData = obj2;
      console.log("43245", this.tradeData);
      let params = {
        operation: "MOD",
        bfpl_info: this.tradeData
      };
      const rule1 = new Promise((resolve, reject) => {
        this.$refs[formName].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      const rule2 = new Promise((resolve, reject) => {
        this.$refs[spotName].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });

      Promise.all([rule1, rule2]).then(() => {
        editAndLossInfo(params)
          .then(res => {
            this.$message({
              message: res.result,
              type: "success"
            });
            this.closeing.closePage(
              this.$store.getters["d2admin/page/allPage"],
              this.$store.getters["d2admin/page/currentPage"]
            );
            this.$router.push({
              path: "/hedging_strategy/tactical_management?type=second"
            });
          })
          .catch(err => {
            this.$message.error(err.msg);
          });
      });
    },
    //增行
    addLine() {
      if (this.ruleForm.strategy_id) {
        this.dialogVisible = true;
        let strategy_id = this.ruleForm.strategy_id;
        this.strategy_id = strategy_id;
      } else {
        this.$message({
          message: "请先选择策略"
        });
      }
    },
    //删行
    delLine() {
      let val = this.listRow;
      if (val.length > 0) {
        for (let i = 0; i < this.listRow.length; i++) {
          val.forEach((val, index) => {
            this.tradeData.forEach((v, i) => {
              if (val.id === v.id) {
                this.tradeData.splice(i, 1);
              }
            });
          });
        }
        this.$refs.table.clearSelection();
      } else {
        this.$message({
          type: "warning",
          message: "请选择删除数据"
        });
      }
    },
    futuresRow(val) {
      this.listRow = val;
    },
    //选择策略
    choose() {
      this.$router.push({ path: "/selectionStrategy" });
    }
  }
};
</script>
<style scoped>
.el-radio {
  width: 100%;
  text-align: center;
  margin-top: 15px;
}
.el-form-item {
  margin-bottom: 0px !important;
}
</style>
